<template>
  <div>
    <!-- Header 头部区域 -->
    <div class="search-header">
      <!-- 后退图标 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="18"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        v-model.trim="kw"
        placeholder="请输入搜索关键词"
        background="#007BFF"
        @input="oinput"
        shape="round"
      />
    </div>

    <!-- 搜索建议 -->
    <div class="sugg-list" v-if="kw.length != 0">
      <div
        class="sugg-item"
        v-for="(item, i) in suggestList"
        :key="i"
        v-html="item"
        @click="gotoSearchResult"
      ></div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="history = []" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item" v-for="(tag, i) in history" :key="i">{{
          tag
        }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { getSuggestListAPI } from "@/api/searchAPI";
export default {
  name: "Search",
  data() {
    return {
      // 搜索关键词
      kw: "",
      // 搜索建议列表
      suggestList: [],
      // 搜索历史
      history: JSON.parse(localStorage.getItem("history")) || [],
    };
  },
  mounted() {
    const ele = document.querySelector("input[type=search]");
    ele && ele.focus();
  },
  methods: {
    oinput() {
      //   清除定时器
      clearTimeout(this.timeId);

      if (this.kw.length == 0) {
        // 清空搜索建议的列表数据
        this.suggestList = [];
        return;
      }
      this.timeId = setTimeout(() => {
        this.initSuggestlist();
      }, 300);
    },
    // 搜索建议列表
    async initSuggestlist() {
      // 调用 API 接口
      const { data: res } = await getSuggestListAPI(this.kw);
      if (res.message === "OK") {
        // 为 suggestList 数据赋值
        this.heightKeywords(res.data.options);
        this.suggestList = res.data.options;
        const newHistory = this.history.filter((item) => item !== this.kw);
        newHistory.unshift(this.kw);
        this.history = newHistory;
      }
    },
    // 定义高亮的关键词的方法
    heightKeywords(arr) {
      if (arr.length == []) {
        return;
      }
      const reg = new RegExp(this.kw, "ig");
      arr.forEach((item,index) => {

        arr[index] = item.replace(reg, (val) => {
          return `<span style="color: red;  ">${val}</span>`;
        });
      });
    },
    gotoSearchResult(e) {
      // this.$router.push(`/search/${e.currentTarget.innerText}`);
      this.$router.push({name:'searchResult',params:{kw:e.currentTarget.innerText}})
    },
  },
  // 监听history发生变化的时候将history存储到localStorage
  watch: {
    history(newVal) {
      localStorage.setItem("history", JSON.stringify(newVal));
    },
  },
};
</script>

<style lang="less" scoped>
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  // 后退按钮
  .goback {
    padding-left: 14px;
  }
  // 搜索组件
  .van-search {
    flex: 1;
  }

  .sugg-list {
    .sugg-item {
      padding: 0 15px;
      border-bottom: 1px solid #f8f8f8;
      font-size: 16px;
      line-height: 50px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>